/**
 * Created by fangshufeng on 2018/4/22.
 */
import React, {Component} from 'react'

import {Select, Divider, Button, Icon, Input, Alert} from 'antd';
import {connect} from 'react-redux'
import {addEnvAction, bind_session} from '../redux/app.redux'
import EditableTable from './EnvTable'
import axios from 'axios'

const {Option, OptGroup} = Select;


class AddEnv extends Component {


    constructor(props) {
        super(props);
        this.protocol = 'http://';
        this.domain = '.com';
        this.envTag = '';
        this.envValue = '';
    }

    _valueChange = (key, v) => {
        this[key] = v;
        const submit = [this.envTag, `${this.protocol}${this.envValue}${this.domain}`];
        let emptyIndex = undefined;
        if (this.envTag === '') {
            emptyIndex = 0
        } else if (this.envValue === '') {
            emptyIndex = 2;
        }
        this.props.submitAction(submit[0], submit[1], emptyIndex);
    };

    selectBefore = _ => (
        <Select defaultValue="http://" style={{width: 90}} onChange={(v) => this._valueChange('protocol', v)}>
            <Option value="http://">http://</Option>
            <Option value="https://">https://</Option>
        </Select>
    );

    selectAfter = _ => (
        <Select defaultValue=".com" style={{width: 80}} onChange={(v) => this._valueChange('domain', v)}>
            <Option value=".com">.com</Option>
            <Option value=".jp">.jp</Option>
            <Option value=".cn">.cn</Option>
            <Option value=".org">.org</Option>
        </Select>
    );

    render() {
        return <div
            style={{...this.props.style, display: 'flex', flexDirection: 'row', justifyContent: 'space-around'}}>
            <Input placeholder='环境名称' style={{width: 80, marginRight: 10}}
                   onChange={(v) => this._valueChange('envTag', v.target.value)}/>
            <Input addonBefore={this.selectBefore()} addonAfter={this.selectAfter()}
                   onChange={(v) => this._valueChange('envValue', v.target.value)}/>
            <Button icon="minus-circle" type='danger' style={{marginLeft: 10}} onClick={() => this.props.delete()}/>
        </div>
    }
}

class EnvSelect extends Component {

    constructor(props) {
        super(props);
        this.state = {
            showEnvTable: false,
            errorMsg: undefined,
        }
        ;
        this.env = '';
        this.envValue = '';
        this.errorMsg = undefined;

        axios.get('/mock/envConfig').then((res) => {
            this.data = res.data.data;
            this.setState({
                businessData: Object.keys(this.data).map(v => {
                    return v;
                }),
            });
        });
    }

    componentDidMount() {
        if (!this.props.socketID) {
            this.props.bind_session();
        }
    }

    render() {
        const {showEnvTable, errorMsg} = this.state;
        return <div style={style.contanier}>
            <div style={style.selectContanier}>
                <div><h2 style={{textAlign: 'center'}}>环境选择</h2></div>
                <Divider dashed/>
                <div style={{display: 'flex'}}>
                    <Select
                        style={style.select}
                        placeholder="请选择需要mock的业务"
                        defaultValue={undefined}
                        onChange={(v) => {
                            this.setState({
                                errorMsg: undefined,
                                showEnvTable: false,
                                envData: this.data[v].routers,
                                business: v,
                                env: undefined,
                                routers: undefined
                            });
                        }}
                        value={this.state.business}
                        size="large"
                    >
                        {!!this.state.businessData && this.state.businessData.map((v, index) => (
                            <Option value={v}
                                    key={index}>{this.data[v].name}</Option>
                        ))}
                    </Select>
                    <Select
                        style={style.select}
                        disabled={!this.state.envData}
                        placeholder="请选择需要mock的环境"
                        defaultValue={undefined}
                        onChange={(v) => {
                            this.setState({
                                errorMsg: undefined,
                                showEnvTable: true,
                                env: v,
                                routers: this.data[this.state.business].routers[v]
                            });
                        }}
                        size="large"
                        value={this.state.env}
                    >
                        {!!this.state.envData && Object.keys(this.state.envData).map((v, index) => (
                            <Option value={v}
                                    key={index}>{v}</Option>
                        ))}
                    </Select>
                </div>
                <Divider dashed/>
                {showEnvTable &&
                <EditableTable style={{margin: '0 20px'}} data={
                    Object.keys(this.state.envData[this.state.env])
                        .map((env) => ({path: env, host: this.state.envData[this.state.env][env]}))}/>}
                {errorMsg !== undefined ? <Alert message={errorMsg} type="error" showIcon/> : null}
                <div style={style.footStyle}>
                    <Button type="primary"
                            onClick={() => {
                                if (!this.state.env) {
                                    this.setState({
                                        errorMsg: '请选择环境',
                                    });
                                    return;
                                }
                                this.props.addEnvAction({business: this.state.business, env: this.state.env});
                                this.props.history.push('/bindDevice');
                            }}
                            style={{width: '30%'}}>
                        确定选择
                    </Button>
                </div>
            </div>

        </div>;
    }
}

const style = {

    contanier: {
        backgroundColor: '#585858',
        width: '100%',
        height: '100%',
        position: 'fixed',
        flexDirection: 'column',
        alignItems: 'center',
        display: 'flex',
        justifyContent: 'center',
        background: `url('/img/back.jpg')`,
        backgroundRepeat: 'round'
    },
    selectContanier: {
        backgroundColor: 'white',
        width: 550,
        height: 'auto',
        borderRadius: 3,
        textAlign: 'center',
        paddingTop: 20,
        paddingBottom: 20
    },
    footStyle: {
        display: 'flex',
        justifyContent: 'space-around',
        marginLeft: '10%',
        marginTop: 20,
        marginRight: '10%'
    },
    select: {flex: 1, margin: '0 20px'}
};

export default connect(state => state.app, {addEnvAction, bind_session})(EnvSelect);